/**
 * Created by three on 14-8-11.
 */

define(['angular','utils/base64', 'func/base/config', 'func/base/service', 'ng/ng.plugins'], function (angular) {
    'use strict';

    /**
     * 定义系统中使用的基础控制器
     */
    angular.module('app.func.base.controller', [
        'app.func.config',
        'app.func.common.service'
    ])
        .controller('AsyncDispatcherCtrl',['$scope','$routeParams','$route','Config',
        function ($scope, $routeParams, $route, config) {
            require([
                'scripts/func/' + $routeParams.module + '/' + $routeParams.func + '-ctrl.js'
            ], function () {
                $route.current.templateUrl  = 'scripts/func/' + $routeParams.module + '/template/' + $routeParams.func + '.html';
                $scope.$apply();
            });
        }])
        .controller('DispatcherCtrl',['$scope','$routeParams','Config','LoadingService',
        function ($scope, $routeParams, config,LoadingService) {

            $scope.config = {};

            var init = function () {
                if(config.funcsData.$resolved) {
                    var funcList = config.currentChildFunc();
                    $scope.listTop = [[]];
                    $scope.rowFunc = [];
                    for(var i=0; i<funcList.length; i++) {
                        if(funcList[i].funcPos==1) { // top
                            $scope.listTop[0].push(funcList[i])
                        } else if(funcList[i].funcPos==2) { // row
                            $scope.rowFunc.push(funcList[i])
                        }
                    }

                    $scope.funcUrl = 'scripts/func/' + $routeParams.module + '/template/' + $routeParams.func + '.html';
                } else {
                    $scope.$on(config.events.appInitialized, init);
                }
            };
            init();

            $scope.action = function (act) {
                $scope.$broadcast(act,{});
            }
        }])
        .controller('DataTableCtrl', ['$scope','AuthenticationService','Config','LoadingService', function ($scope, auth, config,LoadingService) {

            $scope.getAuthTableConfig = function (ajaxUrl, extendConfig) {
                var customerParamsFunc = extendConfig.fnServerParams;
                extendConfig.fnServerParams = null;
                var base_config = {
                    "bProcessing": false,
                    'bLengthChange': false,
                    "bServerSide": true,
                    "sServerMethod": "GET",
                    'bStateSave': false,
                    "bFilter":false,
                    "sAjaxDataProp":"recordList",
                    "bSortClasses":false,
                    "deferRender": true,
                    "ajax":{
                        url: ajaxUrl,
                        type:'GET',
                        xhrFields: {
                            withCredentials: true
                        },
                        beforeSend: function () {
                            LoadingService.loading();
                        },
                        complete: function () {
                            LoadingService.loaded();
                        }
                    },
                    fnServerParams: function ( aoData ) {
                        // 创建提交参数
                        aoData.order_count = aoData.order.length;
                        for(var i=0; i<aoData.order.length; i++ /*var order in aoData.order*/) {
                            var order = aoData.order[i];
                            aoData['order_'+i+'_column'] = aoData.columns[order.column].data
                            aoData['order_'+i+'_dir'] = order.dir
                        }
                        if($scope.user) {
                            for(var k in $scope.user) {
                                aoData[k] = $scope.user[k]
                            }
                        }

                        // 处理客户请求参数
                        customerParamsFunc && customerParamsFunc(aoData);

                        // 删除不需要属性
                        delete aoData.search;
                        delete aoData.columns;
                        delete aoData.order;
                    },
                    "extend": function (obj) {
                        for(var k in obj) {
                            if(obj[k]) {
                                this[k] = obj[k];
                            }
                        }
                        return this;
                    }
                }

                return base_config.extend(extendConfig);
            };

            $scope.manageColumnT1 =  function (data, type, rowData, meta, funcField) {
                if(!funcField) {
                    funcField = 'rowFunc';
                }
                var menuStr =
                    '<div class="requrieCompile"> \
                        <div class="btn-group" style="margin: 3px;" ng-repeat="fun in '+funcField+'"> \
                            <button class="btn btn-xs " ng-click="{{fun.url}}(' + rowData.id + ')" > \
                            <i class="{{fun.icon}}"></i> {{fun.title}} \
                            </button> \
                        </div> \
                    </dev>';
                return menuStr;
            };

            $scope.manageColumnT2 = function (data, type, rowData, meta) {
                var menuStr = '<div class="requrieCompile">';
                for(var i=0; i<$scope.rowFunc.length; i++) {
                    var fun = $scope.rowFunc[i];
                    menuStr +=
                        '<div class="btn-group" style="margin: 3px;"> \
                            <button class="btn btn-xs " ng-click="'+fun.url+'(' + rowData.id + ')" > \
                                        <i class="'+fun.icon+'"></i> '+fun.title+' \
                                        </button> \
                                    </div>';
                }
                menuStr += '</dev>';
                return menuStr;
            };
        }])

        .controller('PageViewController', ['$scope', '$route', '$animate', function ($scope, $route, $animate) {
            console.log('11111')
            // controler of the dynamically loaded views, for DEMO purposes only.
            /*$scope.$on('$viewContentLoaded', function() {

             });*/
        }])

        .controller('LoginPageController', ['$rootScope','$scope','Config','UserFuncService','AuthenticationService','LoadingService','MessageBox',
            function ($rootScope, $scope,config,UserFuncService, AuthenticationService,LoadingService,MessageBox) {
                // your main controller
                $scope.authService = AuthenticationService;

                // 消息事件处理
                var showMessageHandler = function (data) {
                    var boxs = {
                        'success':'success',
                        'info':'info',
                        'error':'error',
                        'warn':'warn',
                        'bsuccess':'bsuccess',
                        'binfo':'binfo',
                        'berror':'berror',
                        'bwarn':'bwarn'
                    };
                    var type = boxs[data.type];
                    MessageBox.modelessBox[type] && MessageBox.modelessBox[type](data.title, data.content, data.config, data.callback)
                };
                var showBoxHandler = function (msg) {
                    MessageBox.modalBox(msg.data, msg.callback);
                };
                // 加载时间处理
                var loadingHandler = function (msg) {
                    if(msg.type=='loading') {
                        LoadingService.loading();
                    } else if(msg.type=='loaded') {
                        LoadingService.loaded();
                    } else if(msg.type=='LoadingModal') {
                        var showMsg = msg['data'] && msg.data['msg'];
                        LoadingService.LoadingModal(showMsg);
                    } else if(msg.type=='LoadedModal') {
                        LoadingService.LoadedModal();
                    }
                };
                // 退出事件处理
                var logoutHandler = function (msg) {
                    AuthenticationService.logout();
                    setTimeout(function () {
                        window.location = msg.loginUrl;
                    }, 1000);
                };
                // 提示消息事件处理
                $rootScope.$on(config.events.showMsg, function (event, msg) {
                    showMessageHandler(msg);
                });
                // 显示box事件处理
                $rootScope.$on(config.events.showBox, function (event, msg) {
                    showBoxHandler(msg);
                });
                // 加载事件处理
                $rootScope.$on(config.events.loading, function (event, msg) {
                    loadingHandler(msg);
                });
                // 退出事件处理
                $rootScope.$on(config.events.logout, function (event, msg) {
                    logoutHandler(msg);
                });
            }])
        .controller('AppController', ['$rootScope','$scope','Config','UserFuncService','AuthenticationService','LoadingService','MessageBox',
        function ($rootScope, $scope,config,UserFuncService, AuthenticationService,LoadingService,MessageBox) {
            // your main controller
            $scope.authService = AuthenticationService;
            $scope.menuPosition = "menu-on-top";

            // 消息事件处理
            var showMessageHandler = function (data) {
                var boxs = {
                    'success':'success',
                    'info':'info',
                    'error':'error',
                    'warn':'warn',
                    'bsuccess':'bsuccess',
                    'binfo':'binfo',
                    'berror':'berror',
                    'bwarn':'bwarn'
                };
                var type = boxs[data.type];
                MessageBox.modelessBox[type] && MessageBox.modelessBox[type](data.title, data.content, data.config, data.callback)
            };
            var showBoxHandler = function (msg) {
                MessageBox.modalBox(msg.data, msg.callback);
            };
            // 加载时间处理
            var loadingHandler = function (msg) {
                if(msg.type=='loading') {
                    LoadingService.loading();
                } else if(msg.type=='loaded') {
                    LoadingService.loaded();
                } else if(msg.type=='LoadingModal') {
                    var showMsg = msg['data'] && msg.data['msg'];
                    LoadingService.LoadingModal(showMsg);
                } else if(msg.type=='LoadedModal') {
                    LoadingService.LoadedModal();
                }
            };
            // 退出事件处理
            var logoutHandler = function (msg) {
                AuthenticationService.logout();
                setTimeout(function () {
                    window.location = msg.loginUrl;
                }, 1000);
            };
            // 提示消息事件处理
            $rootScope.$on(config.events.showMsg, function (event, msg) {
                showMessageHandler(msg);
            });
            // 显示box事件处理
            $rootScope.$on(config.events.showBox, function (event, msg) {
                showBoxHandler(msg);
            });
            // 加载事件处理
            $rootScope.$on(config.events.loading, function (event, msg) {
                loadingHandler(msg);
            });
            // 退出事件处理
            $rootScope.$on(config.events.logout, function (event, msg) {
                logoutHandler(msg);
            });

            // 开始加载数据
            $scope.$emit(config.events.loading, { type: 'LoadingModal' });
            // 菜单数据
            config.funcsData = UserFuncService.detail(function (data) {
                config.funcsData = data;
                if (data && data.$resolved) {
                    var menuList = data.result;

                    config.funcs = {};
                    config.funcsUrl2Id = {};
                    for (var i = 0; i < menuList.length; i++) {
                        var func = menuList[i];
                        // 只处理左边菜单
                        var menu = {
                            name: func.funcCode,
                            url: func.funcAction,
                            title: func.funcName,
                            icon: func.funcIco,
                            funcPos: func.funcPosition,
                            items: [],
                            upId: func.upId,
                            id: func.id
                        };
                        config.funcsUrl2Id[menu.url.trim()] = menu.id;
                        config.funcs['f' + menu.id] = menu;
                    }

                    for (var key in config.funcs) {
                        var menu = config.funcs[key];

                        if (config.funcs['f' + menu.upId]) {
                            config.funcs['f' + menu.upId].items.push(menu);
                        }
                    }

                    $scope.$emit(config.events.loading, { type: 'LoadedModal' });
                    $scope.$broadcast(config.events.appInitialized,{});
                    $scope.$emit(config.events.appInitialized,{});
                }
            });

        }])

        .controller('LangController', ['$scope', 'settings', 'localize', function ($scope, settings, localize) {
            $scope.languages = settings.languages;
            $scope.currentLang = settings.currentLang;
            $scope.setLang = function (lang) {
                settings.currentLang = lang;
                $scope.currentLang = lang;
                localize.setLang(lang);
            }

            // set the default language
            $scope.setLang($scope.currentLang);

        }])
        .controller('LeftPanelCtrl', ['Config','$scope','AuthenticationService','UserFuncService',
            function (config, $scope, AuthServ, UserFuncService) {

                $scope.$emit(config.events.loading, {
                    type: 'LoadingModal',
                    data: {
                        msg: '正在拼命加载，请稍后...'
                    }
                });

                var init = function () {
                    if(config.funcsData.$resolved) {
                        $scope.menuList = [];
                        var menuList = config.funcsData.result;

                        var menuMap = {};
                        for(var i=0; i<menuList.length; i++) {
                            var func = menuList[i];
                            // 只处理左边菜单
                            var menu = {
                                name: func.funcCode,
                                url: func.funcAction,
                                title: func.funcName,
                                icon: func.funcIco,
                                funcPos: func.funcPosition,
                                items: [],
                                upId: func.upId,
                                id: func.id
                            };
                            if(func.funcPosition!=0) {
                                continue;
                            }
                            menuMap['f'+menu.id] = menu;
                        }

                        for(var key in menuMap) {
                            var menu= menuMap[key];

                            if(menuMap['f'+menu.upId]) {
                                menuMap['f'+menu.upId].items.push(menu);
                            } else {
                                $scope.menuList.push(menu);
                            }
                        }

                        $scope.menuList.push(
                            {'name':'demo', 'url': '', 'title': '演示', 'icon': 'fa fa-lg fa-fw fa-table',
                                'items':[
                                    {'name': 'Dashboard', 'url': '/module/demo/dashboard', 'title': '仪表盘', 'icon': 'fa fa-lg fa-fw fa-home'},
                                    {'name': 'amd', 'url': '', 'title': 'amd方式加载', 'icon': 'fa fa-lg fa-fw fa-home',
                                        items:[
                                            {'name': 'about', 'url': '/async/about', 'title': 'About', 'icon': 'fa fa-lg fa-fw fa-table'},
                                            {'name': 'dispatcher1', 'url': '/amd/dispatcher/demo/async-dispatcher1', 'title': 'dispatcher1', 'icon': 'fa fa-lg fa-fw fa-table'},
                                            {'name': 'dispatcher2', 'url': '/amd/dispatcher/demo/async-dispatcher2', 'title': 'dispatcher2', 'icon': 'fa fa-lg fa-fw fa-table'}
                                        ]
                                    },
                                    {'name': 'date', 'url': '/module/demo/date', 'title': 'dateCtrl', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'editor', 'url': '/module/demo/editor', 'title': '编辑框', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'tree', 'url': '/module/demo/tree', 'title': '树视图', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'ztree','url': '/module/demo/ztree','title': 'ztree视图','icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'datagrid', 'url': '/module/demo/datagrid', 'title': '数据表格', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'allcharts', 'url': '', 'title': '各种图表', 'icon': 'fa fa-lg fa-fw fa-table',
                                        items:[
                                            {'name': 'charts', 'url': '/module/demo/charts', 'title': 'echart图表控件', 'icon': 'fa fa-lg fa-fw fa-table'},
                                            {'name': 'plantuml', 'url': '/module/demo/plantuml', 'title': 'plantuml图', 'icon': 'fa fa-lg fa-fw fa-table'}
                                        ]
                                    },
                                    {'name': 'fileupload', 'url': '/module/demo/fileupload', 'title': '图片/文件上传', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'pushmessage', 'url': '', 'title': '消息推送', 'icon': 'fa fa-lg fa-fw fa-table',
                                        items:[
                                            {'name': 'socketio', 'url': '/module/demo/socketio', 'title': 'socket.io', 'icon': 'fa fa-lg fa-fw fa-table'},
                                            {'name': 'sockjs stomp', 'url': '/module/demo/sockjs-stomp', 'title': 'sockjs stomp', 'icon': 'fa fa-lg fa-fw fa-table'}
                                        ]
                                    },

                                    {'name': 'animate', 'url': '/module/demo/animate', 'title': 'angular-animate', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'pagination', 'url': '/module/demo/pagination', 'title': '分页控件', 'icon': 'fa fa-lg fa-fw fa-table'},
                                    {'name': 'ui-bootstrap', 'url': '/module/demo/ui-bootstrap', 'title': 'angular-ui-bootstrap', 'icon': 'fa fa-lg fa-fw fa-table'}
                                ]
                            });
                        $scope.$emit(config.events.loading, {
                            type: 'LoadedModal'
                        });
                    } else {
                        $scope.$on(config.events.appInitialized, init);
                    }
                };
                init();

                $scope.me = AuthServ.currentUser();
            }])

/*
        .controller('WidgetDemoCtrl', ['$scope', '$sce', function ($scope, $sce) {
            $scope.title = 'SmartUI Widget';
            $scope.icon = 'fa fa-user';
            $scope.toolbars = [
                $sce.trustAsHtml('<div class="label label-success">\
				<i class="fa fa-arrow-up"></i> 2.35%\
			</div>'),
                $sce.trustAsHtml('<div class="btn-group" data-toggle="buttons">\
		        <label class="btn btn-default btn-xs active">\
		          <input type="radio" name="style-a1" id="style-a1"> <i class="fa fa-play"></i>\
		        </label>\
		        <label class="btn btn-default btn-xs">\
		          <input type="radio" name="style-a2" id="style-a2"> <i class="fa fa-pause"></i>\
		        </label>\
		        <label class="btn btn-default btn-xs">\
		          <input type="radio" name="style-a2" id="style-a3"> <i class="fa fa-stop"></i>\
		        </label>\
		    </div>')
            ];

            $scope.content = $sce.trustAsHtml('\
						Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\
						tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\
						quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\
						consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\
						cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\
						proident, sunt in culpa qui officia deserunt mollit anim id est laborum.');
        }])
*/

        .controller('ActivityNotifyCtrl', ['$scope','Config','socket', function ($scope, config, Socket) {
            var _this = $scope;
//            var socket = new Socket(_this, config.notify_url);
//            socket.on('sys_msg', function (data) {
//                var msglist = "";
//                for(var i=0; i<arguments.length; i++) {
//                    msglist += '<li>'+arguments[i]+'</li>'
//                }
//                _this.$emit(config.events.showMsg, {
//                    type: 'info',
//                    title: '收到系统消息',
//                    content: msglist
//                });
//            });
//
//            socket.on('personal_MSG', function (data) {
//                var msglist = "";
//                for(var i=0; i<arguments.length; i++) {
//                    var d = arguments[i];
//                    msglist += '<li>'+JSON.stringify(d)+'</li>'
//                }
//                _this.$emit(config.events.showMsg, {
//                    type: 'warn',
//                    title: '收到个人消息',
//                    content: msglist
//                });
//            });

            var ctrl = this;
            ctrl.getDate = function () {
                return new Date().format();
            };

            $scope.refreshCallback = function (contentScope, done) {

                // use contentScope to get access with activityContent directive's Control Scope
                console.log(contentScope);

                // for example getting your very long data ...........
                setTimeout(function () {
                    done();
                }, 3000);

                $scope.footerContent = ctrl.getDate();
            };

            $scope.items = [
                {'title': 'Msgs', 'count': 4, 'src': '/module/demo/animate'},
                {'title': 'Notify', 'count': 4, 'src': '/module/demo/animate'},
                {'title': 'Tasks', 'count': 4, 'src': '/module/demo/animate'},
                {'title': 'animate', 'count': 4, 'src': 'scripts/func/demo/template/animate.html'}
            ];//MessageService.query();
            $scope.total = 0;
            angular.forEach($scope.items, function (item) {
                $scope.total += item.count;
            });

            $scope.footerContent = ctrl.getDate();

        }])
    ;
});
